package com.dycong.common.leetcode.yi;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yilin
 * Date: 2019-08-20
 * Time: 10:05
 */
public class ClosestsThreeSum {

    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[]{-1, 0, 1, 1, 55}, 3));
    }

    public static int threeSumClosest(int[] nums, int target) {

        Arrays.sort(nums);
        int sumResult = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (Math.abs(target - sum) < Math.abs(target - sumResult)) {
                    sumResult = sum;
                }
                if (sum == target) {
                    return target;
                } else if (sum > target) {
//                    while (left<right && nums[left]==nums[left+1]){
//                        left++;
//                    }
                    right--;
                } else {
//                    while (left<right && nums[right]==nums[right-1]){
//                        right--;
//                    }
                    left++;
                }

            }
        }
        return sumResult;
    }
}
